package hui.zhang.service.system.impl;

import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import hui.zhang.dao.system.MenuRepository;
import hui.zhang.dao.system.PermissionRepository;
import hui.zhang.dao.system.RoleRepository;
import hui.zhang.domain.system.Menu;
import hui.zhang.domain.system.Permission;
import hui.zhang.domain.system.Role;
import hui.zhang.domain.system.User;
import hui.zhang.service.system.RoleService;

@Service
@Transactional
public class RoleServiceImpl implements RoleService {

	@Autowired
	private RoleRepository roleRepository;

	@Autowired
	private PermissionRepository permissionRepository;
	
	@Autowired
	private MenuRepository menuRepository;
	
	@Override
	public List<Role> findByUser(User user) {
		// 基于用户查询角色 admin具有所有角色
		if ("admin".equals(user.getUsername())) {
			return roleRepository.findAll();
		} else {
			return roleRepository.findByUser(user.getId());
		}
	}

	@Override
	public List<Role> findAll() {
		return roleRepository.findAll();
	}

	@Override
	public void save(Role model, String[] permissionIds, String menuIds) {
		// 保存角色信息
		roleRepository.save(model);
		// 关联权限
		if(permissionIds != null) {
			for (String permissionId : permissionIds) {
				Permission permission = permissionRepository.findOne(Integer.parseInt(permissionId));
				model.getPermissions().add(permission);
			}
		}
		// 关联菜单
		if(StringUtils.isNoneBlank(menuIds)) {
			String[] array = menuIds.split(",");
			for (String menuId : array) {
				Menu menu = menuRepository.findOne(Integer.parseInt(menuId));
				model.getMenus().add(menu);
			}
		}
	}
	
}
